<?php
/**
 * @Author: lianlianzan(13040@qq.com)
 * @Date:   2018-08-18 16:40:16
 * @Last Modified by:   lianlianzan
 * @Last Modified time: 2022-03-26 23:14:59
 */

namespace app\admin\model;
use app\common\model\BaseModel;

class MerchantRule extends BaseModel {
	// 设置数据表（不含前缀）
	//protected $name = '';

	// 定义时间戳字段名
	protected $createTime = '';
	protected $updateTime = '';

	/**
	 * 取得树形结构的菜单
	 * @param    [type]                    $roleid [description]
	 * @return   [type]                             [description]
	 * @Author   lianlianzan(13040@qq.com)
	 * @DateTime 2017-11-09
	 */
	public function getNewMenuTree($roleid) {
		//获取权限列表
		$accessDao = model('admin/MerchantAccess');
		list($accessList) = $accessDao->search([['roleid', '=', $roleid]]);
		//echo '权限列表:';print_r($accessList);exit;
		$currentModule = strtolower(MODULE_NAME); //模块名(项目名)
		$currentController = strtolower(CONTROLLER_NAME);
		//获取菜单树
		$data = $this->where([['state', '=', 1]])->order('vieworder desc')->select();
		$ruleList = $data->toArray(); //转换为数组
		//print_r($ruleList);
		$nowRule = $selfMenuRule = $subsidiaryArr = array();
		foreach ($ruleList as $key => $value) {
			$value['checked'] = $this->is_checked($value, $roleid, $accessList) ? ' checked' : '';
			if ($value['pid']) {
				$module = $value['module'];
				$controller = $value['controller'];
				$action = $value['action'];
				$value['url'] = url("{$module}/{$controller}/{$action}");
				if (strtolower($module) == $currentModule && strtolower($controller) == $currentController) {
					$value['current'] = 1;
					$nowRule = $value;
				}
				if (strtolower($module) == $currentModule) { //独立菜单
					$selfMenuRule = $value;
				}
				$childs[$value['pid']][$value['id']] = $value;
				//$subs = explode(",", $value['subs']);
				//if (count($subs) > 1) {
				//	$subsidiaryArr = array_merge($subsidiaryArr, $subs);
				//}
			} else {
				$parents[$value['id']] = $value;
			}
		}
		//echo '父级：';print_r($parents);echo '子级：';print_r($childs);echo '当前菜单：';print_r($nowRule);exit;
		//print_r($subsidiaryArr);exit;
		foreach ($parents as $key => $value) {
			//$parents[$key]['items'] = $childs[$key];
			if ($value['id'] == $nowRule['pid']) {
				$parents[$key]['current'] = 1;
			}
			if (isset($childs[$key])) {
				$parents[$key]['hassub'] = 1;
				$parents[$key]['subs'] = $childs[$key];
			} else {
				$parents[$key]['hassub'] = 0;
				$parents[$key]['subs'] = [];
			}
		}
		return array($parents, $selfMenuRule, $subsidiaryArr);
	}

	/**
	 * 检查指定菜单是否有权限
	 * @param array $data menu表中数组
	 * @param int $roleid 需要检查的角色ID
	 */
	protected function is_checked($data, $roleid, $accessArr) {
		if ($data['module'] == '') {
			return false;
		}
		$mdata = array();
		$mdata['roleid'] = $roleid;
		$mdata["m"] = $data['module'];
		$mdata["c"] = $data['controller'];
		$mdata["a"] = $data['action'];
		//print_r($mdata);
		//print_r($accessArr);exit;
		$check = in_array($mdata, $accessArr);
		if ($check) {
			return true;
		} else {
			return false;
		}
	}

	public function getTree($map) {
		$data = $this->where($map)->order('vieworder desc')->select();
		$data = $data->toArray(); //转换为数组
		//print_r($this->getLastSql());
		return $this->parseTree($data);
	}

	private function parseTree($data) {
		$isopen_config = config('engineeconfig.isopen_config');
		$yes_config = config('engineeconfig.yes_config');

		$parents = $childs = array();
		foreach ($data as $key => $value) {
			$value['state_show'] = $isopen_config[$value['state']];
			$value['display_show'] = $yes_config[$value['display']];
			$value['is_selfmenu_show'] = $yes_config[$value['is_selfmenu']];

			if ($value['pid']) {
				$childs[$value['pid']][$value['id']] = $value;
			} else {
				$parents[$value['id']] = $value;
			}
		}
		//print_r($parents);exit;
		//print_r($childs);exit;

		foreach ($parents as $key => $value) {
			//$parents[$key]['ischild'] = $childs[$key];
			if (isset($childs[$key])) {
				$parents[$key]['hassub'] = 1;
				$parents[$key]['subs'] = $childs[$key];
			} else {
				$parents[$key]['hassub'] = 0;
				$parents[$key]['subs'] = [];
			}
		}
		//print_r($parents);exit;

		return array($parents);
	}

	public function getParentList() {
		$map = [
			['pid', '=', 0]
		];
		$data = $this->where($map)->order('vieworder desc')->select();
		return $this->parseByKey($data, '');
	}

	/**
	 * 菜单树状结构集合
	 */
	public function getMenuTree($cateId, $groupid) {
		$data = $this->get_tree($cateId, $groupid, 0, 0);
		//print_r($data);
		return $data;
	}

	//取得树形结构的菜单
	public function get_tree($cateId, $groupid=0, $myid, $parent="", $Level=1) {
		//print_r($groupid);
		$data = $this->admin_menu($cateId, $myid, $groupid);
		// echo $myid.'<br>';
		//print_r($data);
		//echo '<br>';
		// if ($Level == 2) {
		// 	exit;
		// }
		$retData = [];
		$Level++;
		if (is_array($data)) {
			foreach ($data as $key => $value) {
				$id = $value['id'];
				//$model = ucwords($a['model']);
				//$controller = ucwords($a['controller']);
				$module = $value['module'];
				$controller = $value['controller'];
				$action = $value['action'];
				//附带参数
				$fu = "";
				// if ($a['data']) {
				// 	$fu = "?" . $a['data'];
				// }
				$array = array(
					"icon"	 => $value['icon'],
					"id"	 => $id,
					"name"	 => $value['name'],
					"parent" => $parent,
					"controller" => $controller,
					//"navFlag" => $a['nav_flag'],
					//'sideFlag' => strtolower($module).'_'.strtolower($controller),
					'sideFlag' => $module.'_'.$controller,
					//"btn_class" => $value['btn_class'] ? $value['btn_class'] : 'btn-default',
					//"color"		=> $a['color'],
					"url"	 => url("{$module}/{$controller}/{$action}", ['menucid'=>$value['cid']]),
					"display"=> $value['display'],
					//'is_my_menu' => $a['is_my_menu']
				);

				$retData[$id] = $array;

				if ($value['has_sub']) {
					$child = $this->get_tree($cateId, $groupid, $value['id'], $id, $Level);
					//print_r($child);exit;
					if ($child) {
						$array['url'] = '';
					}
					//由于后台管理界面只支持三层，超出的不层级的不显示
					if ($child && $Level <= 2) {
						$retData[$id]['items'] = $child;
					}
				}
			}
			return $retData;
		}
		return false;
	}

	/**
	 * 按父ID查找菜单子项
	 * @param integer $parentid   父菜单ID
	 * @param integer $with_self  是否包括他自己
	 */
	public function admin_menu($cateId = 0, $parentid, $groupid, $with_self = false) {
		//父节点ID
		$parentid = (int) $parentid;
		$result = $this->where(array('cid'=>$cateId, 'pid'=>$parentid, 'state'=>1))->order('vieworder desc')->select();
		$result = $result->toArray(); //转换为数组
		//print_r($this->getLastSql());echo '<br>';
		if ($with_self) {
			$result2[] = $this->where(array('id' => $parentid))->find();
			$result = array_merge($result2, $result);
		}
		//print_r($result);

		//权限检查
		//$groupid = session("s_groupid");
		//print_r($groupid);

		$privdb = model('common/AuthAccess'); //实例化权限表

		$array = array();
		foreach ($result as $v) {
			//方法
			$action = $v['action'];
			//public开头的通过
			if (preg_match('/^public_/', $action)) {
				$array[] = $v;
			} else {
				if (preg_match('/^ajax_([a-z]+)_/', $action, $_match)) {
					$action = $_match[1];
				}
				$map = array(
					'm' 		=> $v['module'],
					'c' 		=> $v['controller'],
					//'a' 		=> $action,
					'groupid' 	=> $groupid,
				);
				$check = $privdb->where($map)->find();
				//echo $privdb->getLastSql();echo '<br>';
				if ($check) {
					$array[] = $v;
				}
			}
		}
		//print_r($array);

		return $array;
	}

	public function countSearch($map) {
		return $this->where($map)->count();
	}

	public function search($map, $limit='') {
		$data = $this->where($map)->order('create_time desc')->limit($offset, $limit)->select();
		$data = $data->toArray(); //转换为数组
		return $this->parseSearch($data);
	}

	protected function parseSearch($data) {
		$ftpWeb = config('app.ftp_web');
		$isopen_config = config('engineeconfig.isopen_config');

		$list = array();
		foreach ($data as $key => $value) {
			//通用解析
			//$value['create_time_show'] = $value['create_time'] ? date("Y-m-d H:i:s", $value['create_time']) : '';
			//$value['state_show'] = isset($value['state']) ? $isopen_config[$value['state']] : '';
			//$value['picurl'] = $value['picurl'] ? $ftpWeb.$value['picurl'] : '';
			//通用解析

			$list[$value['id']] = $value;
		}
		return array($list);
	}

	protected function parseInfo($info) {
		$ftpWeb = config('app.ftp_web');
		$isopen_config = config('engineeconfig.isopen_config');

		//通用解析
		//$info['create_time_show'] = $info['create_time'] ? date("Y-m-d H:i:s", $info['create_time']) : '';
		//$info['state_show'] = isset($info['state']) ? $isopen_config[$info['state']] : '';
		//$info['picurl'] = $info['picurl'] ? $ftpWeb.$info['picurl'] : '';
		//通用解析

		return $info;
	}

}